﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Evpo.ContactData.ViewModel;
using Evpo.ContactData.Common;

namespace Evpo.ContactData.UI
{
    public partial class NameValueLookup : System.Web.UI.UserControl
    {
        public NameValueLookup()
        {
            Multiselect = false;
        }

        #region Properties
        public List<int> SelectedItems
        {
            get;
            set;
        }

        public string LookupName
        {
            get;
            set;
        }

        public string LookupHiddenID
        {
            get;
            set;
        }

        protected NameLookupViewModel Model
        {
            get;
            set;
        }

        public bool Multiselect
        {
            get;
            set;
        }
        #endregion Properties

        #region Events
        public event SelectedItemsChangedEventHandler SelectedItemsChanged;
        private void OnSelectedItemsChanged(SelectedItemsChangedEventArgs e)
        {
            if (SelectedItemsChanged != null)
                SelectedItemsChanged(this, e);
        }
        #endregion Events

        #region Fields
        private List<int> _selectedItemIndexes = new List<int>();
        #endregion Fields

        #region Methods
        #endregion

        #region Handlers
        protected void Page_Init(object sender, EventArgs e)
        {
            uiGridView.RowDataBound += new GridViewRowEventHandler(uiGridView_RowDataBound);

            uiGridView.Columns[0].Visible = Multiselect;
            uiGridView.Columns[1].Visible = !Multiselect;
        }

        void uiGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            IDictionaryItem item = e.Row.DataItem as IDictionaryItem;
            if (item == null)
                return;

            if (!SelectedItems.Contains(item.ID))
                return;

            if (Multiselect)
            {
                ((CheckBox)e.Row.FindControl("uiSelected")).Checked = true;
            }
            else
            {
                _selectedItemIndexes.Add(e.Row.RowIndex);
            }
        }

        protected void uiGridView_DataBound(object sender, EventArgs e)
        {
            if (_selectedItemIndexes.Count > 0)
            {
                uiGridView.SelectedIndex = _selectedItemIndexes[0];
            }
            else
            {
                uiGridView.SelectedIndex = -1;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            Model = new NameLookupViewModel(
                (IConnection)Session[SessionStateKeys.Connection],
                LookupName);

            uiLabel.Text = Model.GetLookupDisplayName();
            if(!String.IsNullOrEmpty(LookupHiddenID))
                uiReturn.HiddenElementID = LookupHiddenID;
        }

        protected void uiDataSource_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            e.InputParameters["model"] = Model;
        }

        protected void uiDataSource_Updating(object sender, ObjectDataSourceMethodEventArgs e)
        {
            e.InputParameters["model"] = Model;
        }

        protected void uiDataSource_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
        {
            e.InputParameters["model"] = Model;
        }

        protected void uiDataSource_Deleting(object sender, ObjectDataSourceMethodEventArgs e)
        {
            e.InputParameters["model"] = Model;

            if (uiGridView.Rows.Count == 1 && uiGridView.PageIndex > 0)
            {
                uiGridView.PageIndex--;
            }

        }

        protected void uiCreate_Click(object sender, EventArgs e)
        {
            uiDataSource.Insert();
            uiCreatedName.Text = String.Empty;
        }

        protected void ItemSelectionChanged(int id, bool isChecked)
        {
            if (isChecked)
            {
                if (!Multiselect)
                {
                    SelectedItems.Clear();
                    //ClearSelectedOfNotSelected(id);
                }

                SelectedItems.Add(id);
            }
            else
            {
                SelectedItems.RemoveAt(
                    SelectedItems.FindIndex(i => i == id)
                    );

                if (!Multiselect && SelectedItems.Count == 0)
                {
                    SelectedItems.Add(Model.GetIDForUnspecified());
                }
            }

            SelectedItemsChangedEventArgs arg = new SelectedItemsChangedEventArgs();
            arg.SelectedItems = this.SelectedItems;
            OnSelectedItemsChanged(arg);

        }

        protected void uiGridView_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (uiGridView.SelectedValue == null)
                return;

            int selectedItemID = -1;
            bool isChecked = false;

            if(uiGridView.SelectedRow == null)
            {
                selectedItemID = SelectedItems[0];
            }
            else
            {
                isChecked = true;
                selectedItemID = (int)uiGridView.SelectedValue;
            }

            ItemSelectionChanged(selectedItemID, isChecked);
        }

        protected void uiSelected_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox chk = (CheckBox)sender;
            HiddenField hid = (HiddenField)chk.Parent.FindControl("uiKey");
            
            int id;
            if (!Int32.TryParse(hid.Value, out id))
                return;
            ItemSelectionChanged(id, chk.Checked);
        }

        private void ClearSelectedOfNotSelected(int selectedID)
        {
            foreach (GridViewRow row in uiGridView.Rows)
            {
                HiddenField hid = (HiddenField)row.FindControl("uiKey");
                int id;
                if (!Int32.TryParse(hid.Value, out id))
                    continue;
                if (id == selectedID)
                    continue;
                
                CheckBox chk = (CheckBox)row.FindControl("uiSelected");
                chk.Checked = false;
            }
        }
        #endregion Handlers

    }

    public delegate void SelectedItemsChangedEventHandler(object sender, SelectedItemsChangedEventArgs e);

    public class SelectedItemsChangedEventArgs : EventArgs
    {
        public SelectedItemsChangedEventArgs()
        {
            SelectedItems = new List<int>();
        }

        public List<int> SelectedItems
        {
            get;
            set;
        }
    }
}